<template>
  <div class="cart-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">
          <i class="icon-arrow-left"></i>
        </button>
        <h1 class="page-title">购物车</h1>
      </div>
      <button v-if="cartItems.length > 0" class="clear-btn" @click="clearCart">
        清空
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <span>处理中...</span>
    </div>

    <!-- 空购物车状态 -->
    <div v-else-if="cartItems.length === 0" class="empty-cart">
      <div class="empty-icon">🛒</div>
      <div class="empty-text">购物车是空的</div>
      <button class="go-shopping-btn" @click="goToHome">去购物</button>
    </div>

    <!-- 购物车内容 -->
    <div v-else class="cart-content">
      <!-- 购物车商品列表 -->
      <div class="cart-items">
        <div 
          class="cart-item" 
          v-for="item in cartItems" 
          :key="item.id"
        >
          <!-- 商品图片 -->
          <div class="item-image">
            <img 
              v-if="item.productImage" 
              :src="item.productImage" 
              :alt="item.productName"
              class="product-image"
            />
            <div v-else class="product-image-placeholder">
              {{ item.productName }}
            </div>
          </div>

          <!-- 商品信息 -->
          <div class="item-info">
            <div class="item-name">{{ item.productName }}</div>
            <div class="item-price">¥{{ item.price }}</div>
            
            <!-- 数量控制 -->
            <div class="quantity-control">
              <button 
                class="quantity-btn" 
                @click="decreaseQuantity(item)"
                :disabled="item.quantity <= 1"
              >
                -
              </button>
              <span class="quantity">{{ item.quantity }}</span>
              <button 
                class="quantity-btn" 
                @click="increaseQuantity(item)"
              >
                +
              </button>
            </div>
          </div>

          <!-- 删除按钮 -->
          <button class="remove-btn" @click="removeItem(item)">
            <i class="icon-delete">🗑️</i>
          </button>
        </div>
      </div>

      <!-- 购物车底部 -->
      <div class="cart-footer">
        <div class="cart-summary">
          <div class="total-items">
            共 {{ totalItems }} 件商品
          </div>
          <div class="total-price">
            总计: <span class="price">¥{{ totalPrice }}</span>
          </div>
        </div>
        <button class="checkout-btn" @click="showCheckoutModal">
          结算 ({{ totalItems }})
        </button>
      </div>
    </div>

    <!-- 收货信息输入弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">填写收货信息</h3>
          <button class="modal-close" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label class="form-label">收货人姓名</label>
            <input 
              v-model="receiverInfo.name" 
              type="text" 
              class="form-input" 
              placeholder="请输入收货人姓名"
              maxlength="20"
            />
          </div>
          <div class="form-group">
            <label class="form-label">联系电话</label>
            <input 
              v-model="receiverInfo.phone" 
              type="tel" 
              class="form-input" 
              placeholder="请输入联系电话"
              maxlength="11"
            />
          </div>
          <div class="form-group">
            <label class="form-label">收货地址</label>
            <textarea 
              v-model="receiverInfo.address" 
              class="form-textarea" 
              placeholder="请输入详细收货地址"
              rows="3"
              maxlength="200"
            ></textarea>
          </div>
          <div class="form-group">
            <label class="form-label">备注（可选）</label>
            <textarea 
              v-model="receiverInfo.remark" 
              class="form-textarea" 
              placeholder="请输入备注信息"
              rows="2"
              maxlength="100"
            ></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeModal">取消</button>
          <button class="btn btn-primary" @click="confirmCheckout" :disabled="!isFormValid">
            确认结算
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import { usePaymentStore } from '@/stores/payment'

// 路由
const router = useRouter()

// 状态管理
const cartStore = useCartStore()
const userStore = useUserStore()
const paymentStore = usePaymentStore()

// 响应式数据
const loading = ref(false)
const showModal = ref(false) // 控制弹窗显示
const receiverInfo = ref({ // 收货信息
  name: '',
  phone: '',
  address: '',
  remark: ''
})

// 计算属性
const cartItems = computed(() => cartStore.cartItems)
const totalItems = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0).toFixed(2)
})

// 表单验证
const isFormValid = computed(() => {
  return receiverInfo.value.name && receiverInfo.value.phone && receiverInfo.value.address
})

// 生命周期
onMounted(() => {
  loadCart()
})

// 方法
const loadCart = async () => {
  const userId = userStore.user?.id
  if (userId) {
    loading.value = true
    try {
      await cartStore.fetchCart(userId)
    } catch (error) {
      console.error('加载购物车失败:', error)
    } finally {
      loading.value = false
    }
  }
}

const goBack = () => {
  router.back()
}

const goToHome = () => {
  router.push('/')
}

const increaseQuantity = async (item: any) => {
  const userId = userStore.user?.id
  if (userId) {
    try {
      await cartStore.update(userId, item.productId, item.quantity + 1)
    } catch (error) {
      console.error('更新数量失败:', error)
    }
  }
}

const decreaseQuantity = async (item: any) => {
  if (item.quantity <= 1) return
  
  const userId = userStore.user?.id
  if (userId) {
    try {
      await cartStore.update(userId, item.productId, item.quantity - 1)
    } catch (error) {
      console.error('更新数量失败:', error)
    }
  }
}

const removeItem = async (item: any) => {
  if (!confirm('确定要删除这个商品吗？')) {
    return
  }
  
  const userId = userStore.user?.id
  if (userId) {
    try {
      await cartStore.remove(userId, item.productId)
    } catch (error) {
      console.error('删除商品失败:', error)
    }
  }
}

const clearCart = async () => {
  if (!confirm('确定要清空购物车吗？')) {
    return
  }
  
  const userId = userStore.user?.id
  if (userId) {
    try {
      await cartStore.clear(userId)
    } catch (error) {
      console.error('清空购物车失败:', error)
    }
  }
}

const showCheckoutModal = () => {
  receiverInfo.value = { // 清空收货信息
    name: '',
    phone: '',
    address: '',
    remark: ''
  }
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
}

const confirmCheckout = async () => {
  if (cartItems.value.length === 0) { // 如果购物车为空
    alert('购物车是空的') // 提示用户
    return
  }
  
  const userId = userStore.user?.id // 获取用户ID
  if (!userId) { // 如果用户未登录
    alert('请先登录') // 提示用户
    return
  }
  
  // 检查是否有收货信息
  if (!isFormValid.value) {
    alert('请填写完整的收货信息')
    return
  }
  
  try {
    loading.value = true // 开始加载
    
    // 准备购物车商品数据
    const items = cartItems.value.map(item => ({ // 映射购物车商品
      productId: item.productId, // 商品ID
      productName: item.productName || '未知商品', // 商品名称
      productImage: item.productImage || '', // 商品图片
      price: item.price || 0, // 商品价格
      quantity: item.quantity || 1, // 商品数量
      subtotal: (item.price || 0) * (item.quantity || 1) // 小计
    }))
    
    // 创建订单数据
    const orderData = {
      totalAmount: parseFloat(totalPrice.value), // 总金额
      receiverName: receiverInfo.value.name, // 收货人姓名
      receiverPhone: receiverInfo.value.phone, // 联系电话
      receiverAddress: receiverInfo.value.address, // 收货地址
      paymentMethod: 'ALIPAY', // 默认支付方式
      remark: receiverInfo.value.remark, // 备注
      items: items // 购物车商品列表
    }
    
    // 创建订单
    const result = await paymentStore.createOrder(userId, orderData) // 调用创建订单方法
    
    if (result.success) { // 如果创建成功
      closeModal() // 关闭弹窗
      // 跳转到支付页面
      router.push('/payment') // 跳转到支付页面
    } else { // 如果创建失败
      alert(result.message || '创建订单失败') // 提示用户
    }
  } catch (error) {
    console.error('创建订单失败:', error) // 打印错误信息
    alert('创建订单失败，请重试') // 提示用户
  } finally {
    loading.value = false // 结束加载
  }
}
</script>

<style scoped>
.cart-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #333;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.clear-btn {
  background: none;
  border: none;
  color: #dc3545;
  font-size: 14px;
  cursor: pointer;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 60px;
  color: #ccc;
  margin-bottom: 16px;
}

.empty-text {
  color: #666;
  margin-bottom: 20px;
  font-size: 16px;
}

.go-shopping-btn {
  padding: 12px 24px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.cart-content {
  padding: 16px;
}

.cart-items {
  margin-bottom: 16px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.item-image {
  margin-right: 12px;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.product-image-placeholder {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  text-align: center;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.item-price {
  font-size: 18px;
  font-weight: 600;
  color: #e74c3c;
  margin-bottom: 12px;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 12px;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 600;
}

.quantity-btn:disabled {
  background-color: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

.quantity {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  min-width: 40px;
  text-align: center;
}

.remove-btn {
  background: none;
  border: none;
  color: #dc3545;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.remove-btn:hover {
  background-color: #f8d7da;
}

.cart-footer {
  position: fixed; /* 固定定位 */
  bottom: 60px; /* 距离底部60px，为底部导航菜单留出空间 */
  left: 0;
  right: 0;
  background-color: #fff; /* 背景色 */
  padding: 16px; /* 内边距 */
  border-top: 1px solid #eee; /* 顶部边框 */
  display: flex; /* 弹性布局 */
  justify-content: space-between; /* 两端对齐 */
  align-items: center; /* 垂直居中 */
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1); /* 阴影效果 */
  z-index: 999; /* 确保在TabBar之下但在其他内容之上 */
}

.cart-summary {
  flex: 1; /* 弹性增长 */
}

.total-items {
  font-size: 14px; /* 字体大小 */
  color: #666; /* 颜色 */
  margin-bottom: 4px; /* 底部外边距 */
}

.total-price {
  font-size: 16px; /* 字体大小 */
  color: #333; /* 颜色 */
}

.price {
  font-size: 18px; /* 字体大小 */
  font-weight: 600; /* 字体粗细 */
  color: #e74c3c; /* 价格颜色 */
}

.checkout-btn {
  padding: 12px 24px; /* 内边距 */
  background-color: #e74c3c; /* 背景色 */
  color: white; /* 颜色 */
  border: none; /* 无边框 */
  border-radius: 4px; /* 圆角 */
  cursor: pointer; /* 鼠标指针 */
  font-size: 16px; /* 字体大小 */
  font-weight: 500; /* 字体粗细 */
  min-width: 120px; /* 最小宽度 */
  transition: background-color 0.3s ease; /* 过渡动画 */
}

.checkout-btn:hover {
  background-color: #c0392b; /* 悬停时背景色 */
}

.checkout-btn:active {
  transform: translateY(1px); /* 点击时轻微下移 */
}

/* 为底部购物车和导航菜单留出空间 */
.cart-content {
  padding-bottom: 120px; /* 增加底部内边距，为结算按钮和导航菜单留出空间 */
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 450px;
  max-height: 90%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
  background-color: #f8f8f8;
}

.modal-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.modal-close:hover {
  background-color: #eee;
}

.modal-body {
  padding: 16px;
  overflow-y: auto;
  flex-grow: 1;
}

.form-group {
  margin-bottom: 16px;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #555;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  box-sizing: border-box;
  transition: border-color 0.2s;
}

.form-input:focus,
.form-textarea:focus {
  border-color: #007bff;
  outline: none;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid #eee;
  background-color: #f8f8f8;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-primary:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
}
</style> 